<?php
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.model');

class auctionModelHistory extends JModel
{

	function getList()
	{ 
		global $mainframe;
		$session =& JFactory::getSession();
		
		// Initialize variables
		$db		=& $this->getDBO();

		if (!empty($this->_list)) {
			return $this->_list;
		}
		
		if(JRequest::getVar('auction_id')){
			$session->set('auction_id', JRequest::getVar('auction_id'));
		}
		$search = null;
		$where = array();

		$this->_search['search_date']	= JRequest::getVar('search_date');
		if ($this->_search['search_date']) {
			$where[] = "a.auction_date = '".$this->_search['search_date']."'";
		}
		
		//$where[] = ' id = '. $session->get('auction_id');
		$where[] = ' a.closed = 1';
		$where = (count($where) ? ' WHERE '.implode(' AND ', $where) : '');


		// Get some variables from the request
		$option				= JRequest::getCmd( 'option' );
		$limit				= $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart			= $mainframe->getUserStateFromRequest('sessions.limitstart', 'limitstart',		0,	'int');


		// Get the total number of records
		$query = 'SELECT COUNT(*) FROM #__auction a '. $where;
		$db->setQuery($query);
		$total = $db->loadResult();

		// Create the pagination object
		jimport('joomla.html.pagination');
		$this->_page = new JPagination($total, $limitstart, $limit);

		// Get the articles
		$query = 'SELECT *, a.id as id, a.published as published ' .
				' FROM #__auction as a LEFT JOIN #__pr_product as p ON a.product_id = p.id ' 
				. $where 
				. ' ORDER BY STR_TO_DATE(auction_date,"%d-%m-%Y") DESC, p.katno DESC'; //die($query);
		
		$db->setQuery($query, $this->_page->limitstart, $this->_page->limit);
		$this->_list = $db->loadObjectList();
		//print_r ($this->_list);exit();
		//If there is a db query error, throw a HTTP 500 and exit
		if ($db->getErrorNum()) {
			JError::raiseError( 500, $db->stderr() );
			return false;
		}

		return $this->_list;
	}

	function getPagination()
	{
		if (is_null($this->_list) || is_null($this->_page)) {
			$this->getList();
		}
		return $this->_page;
	}
	
	function getSearch()
	{
		return $this->_search;
	}
}